﻿using System;
using Jink.Core.Converters.Annotations;
using Jink.Core.Json.Values;
using XenoGears.Strings;

namespace Jink.Core.Json.Converters.Scalars
{
    [Converter]
    internal static class ScalarSerializers
    {
        [Converter(Weight = 0.5)]
        public static JsonValue ToJson(int inum)
        {
            return new JsonExpression(inum.ToInvariantString());
        }

        [Converter(Weight = 0.5)]
        public static JsonValue ToJson(double fnum)
        {
            return new JsonExpression(fnum.ToInvariantString());
        }

        [Converter(Weight = 0.5)]
        public static JsonValue ToJson(String s)
        {
            return new JsonExpression(s.ToJsonString());
        }

        [Converter(Weight = 0.5)]
        public static JsonValue ToJson(bool flag)
        {
            return new JsonExpression(flag ? "true" : "false");
        }

        [Converter(Weight = 0.5)]
        public static JsonValue ToJson(DateTime dateTime)
        {
            var utc = dateTime.ToUniversalTime();
            return new JsonExpression(String.Format("Date.UTC({0}, {1}, {2}, {3}, {4}, {5}, {6})",
                utc.Year, utc.Month, utc.Day, utc.Hour, utc.Minute, utc.Second, utc.Millisecond));
        }

        [Converter(Weight = 0.5)]
        public static JsonValue ToJson(Guid guid)
        {
            return new JsonExpression("'{" + guid.ToInvariantString() + "}'");
        }

        [Converter(Weight = 0.5)]
        public static JsonValue ToJson<T>(T? nullable)
            where T : struct
        {
            return nullable.HasValue ? nullable.Value.ToJson() : new JsonExpression("null");
        }
    }
}
